使用Django內建的paginator分頁類別
將原本的Quryset物件(doc_warehouse.objects.all().order_by("id"))丟進Paginator內
他會用你給的limit去切資料
然後將每一頁都指定給Doc_warehouse保持我們原本的templates內的邏輯可以保持不變
doc_info/views.py
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
def doc_main(request):
doc_all = doc_warehouse.objects.all().order_by("id")
limit = 20
page = request.GET.get('page', 1)
paginator = Paginator(doc_all, limit)
try:
Doc_warehouse = paginator.page(page)
except PageNotAnInteger:
Doc_warehouse = paginator.page(1)
except EmptyPage:
Doc_warehouse = paginator.page(paginator.num_pages)
context = {
'Doc_warehouse': Doc_warehouse,
}
return render(request, 'doc/main.html', context)
@login_required()
def doc_user_list(request):
user = request.user
doc_filter = doc_warehouse.objects.filter(user_id=user.id).order_by("id")
limit = 5
page = request.GET.get('page', 1)
paginator = Paginator(doc_filter, limit)
try:
Doc_warehouse = paginator.page(page)
except PageNotAnInteger:
Doc_warehouse = paginator.page(1)
except EmptyPage:
Doc_warehouse = paginator.page(paginator.num_pages)
context = {
'Doc_warehouse': Doc_warehouse,
}
return render(request, 'doc/user_list.html', context)
templates的最下面增加以下
templates/main.html & templates/user_list.html
<p>
{% for page_number in Doc_warehouse.paginator.page_range %}
{% ifequal page_number Doc_warehouse.number %}
{{ page_number }}
{% else %}
<a href="?page={{ page_number }}">{{ page_number }}</a>
{% endifequal %}
{% endfor %}
</p>
效果呈現如下